package com.stu.intercept;


import com.stu.common.BaseContext;
import com.stu.common.PathMatcher;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 *  实现接口
 *  spring管理
 *  拦截器
 *  单体项目 拦截路径 在容器中存在 mapping 关系 才能拦截
 */
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1、获取本次请求的URI
        String requestURI = request.getRequestURI();
        //log.info("拦截到请求：{}",requestURI);
        //2、判断本次请求是否需要处理
        boolean check = PathMatcher.check(requestURI);
        //3、如果不需要处理，则直接放行
        if(check){
            //log.info("本次请求{}不需要处理",requestURI);
            return true;
        }
        //4、判断登录状态，如果已登录，则直接放行
        Long user = (Long)request.getSession().getAttribute("user");
        if(user != null) {
            log.info("用户已登录，用户id为：{}", user);
            BaseContext.setCurrentId(user);
            return true;
        }
        log.info("用户未登录");
        //5、如果未登录则返回未登录结果，通过输出流方式向客户端页面响应数据
        //response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        response.setStatus(401);
        throw new RuntimeException("NOTLOGIN");
        //return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
